<template>
  <div>
    <div v-show="!flag">
      <div style="text-align:left;">
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="菜单名称">
                <el-input placeholder="请输入菜单名称" v-model="menuName" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            </el-form-item>
            <el-button type="primary" round style="float: right;margin-right:20px" @click="flag = true"><i class="el-icon-setting"></i> 设置角色菜单</el-button>
        </el-form>
      </div>
      <el-table :data="tableData" border style="width: 100%">
          <el-table-column fixed prop="menuName" label="菜单名称" width="190"></el-table-column>
          <el-table-column prop="menuUrl" label="菜单URL" width="280"></el-table-column>
          <el-table-column prop="parentId" label="父级菜单" width="180" :formatter="formatterParent"></el-table-column>
          <el-table-column prop="menuIcon" label="菜单图标class" width="280"></el-table-column>
          <el-table-column prop="menuState" label="菜单状态" width="130" :formatter="formatState"></el-table-column>
          <el-table-column label="操作" width="150" fit='true'>
              <template slot-scope="scope">
                  <el-button type="text" v-show="scope.row.menuState==0" @click="delMenu1(scope.row.menuId)"><i class="el-icon-error"></i>禁用</el-button>
                  <el-button type="text" v-show="scope.row.menuState==1" @click="delMenu2(scope.row.menuId)"><i class="el-icon-success"></i>启用</el-button>
              </template>
          </el-table-column>
      </el-table>
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[3, 5, 9, 15]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </div>
    <!-- 设置角色菜单div -->
    <div  v-show="flag">
      <h1 style="font-size:35px;text-align:center;width:500px;font-family: 华文行楷;">设置角色菜单</h1>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-select v-model="roleId" placeholder="请选择角色" @change="showChecked">
            <el-option
              v-for="item in roles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-tree
              :data="menus"
              show-checkbox
              @check="clickTreeCheckbox"
              ref="tree"
              default-expand-all
              :check-strictly="systemNodeFlag"
              node-key="menuId"
              :props="defaultProps">
            </el-tree>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple" style="text-align:left">
              <el-button type="primary" plain @click="submitTree">提交修改</el-button>
              <el-button type="success" plain  @click="flag = false">返回列表</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Menu',
  data () {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      menuName: '',
      menus: [],
      formatMenu: [],
      roles: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      checkeds: [],
      roleId: '',
      flag: false,
      systemNodeFlag: false
    }
  },
  methods: {
    // 加载菜单和角色的方法
    initMenu () {
      this.$axios.post(`/api/DHMenuController/initMenu?pageNum=${this.currentPage}&pageSize=${this.pageSize}&menuName=${this.menuName}`).then(({data}) => {
        this.tableData = data.rows
        this.total = data.total
      })
    },
    // 格式化父级ID
    formatterParent (row, column, cellValue, index) {
      if (row.parentId === 0) {
        return '无'
      } else {
        for (let i = 0; i < this.formatMenu.length; i++) {
          if (this.formatMenu[i].menuId === row.parentId) {
            return this.formatMenu[i].menuName
          }
        }
      }
    },
    // 格式化状态
    formatState (row, column, cellValue, index) {
      return row.menuState === 0 ? '正常' : row.menuState === 1 ? '禁用' : '未知'
    },
    // 改变页大小
    handleSizeChange (value) {
      this.pageSize = value
      this.initMenu()
    },
    // 改变当前页码
    handleCurrentChange (value) {
      this.currentPage = value
      this.initMenu()
    },
    // 查询按钮
    search () {
      this.currentPage = 1
      this.initMenu()
    },
    // 设置菜单查询菜单和角色
    showMenu () {
      this.$axios.post(`/api/DHMenuController/queryAllMenu`).then(({data}) => {
        this.menus = this.arraytotree(data)
        this.formatMenu = data
        this.initMenu()
      })
      this.$axios.post(`/api/DHRoleController/findAllRole`).then(({data}) => {
        this.roles = data
      })
    },
    // 组装菜单的方法
    arraytotree (arr) {
      var top = []
      var sub = []
      var tempObj = {}
      arr.forEach(function (item) {
        if (item.parentId === 0) { // 顶级分类
          top.push(item)
        } else {
          sub.push(item) // 其他分类
        }
        item.children = [] // 默然添加children属性
        tempObj[item.menuId] = item // 用当前分类的id做key，存储在tempObj中
      })

      sub.forEach(function (item) {
        // 取父级
        var parent = tempObj[item.parentId] || {'children': []}
        // 把当前分类加入到父级的children中
        parent.children.push(item)
      })

      return top
    },
    // 显示角色菜单的方法
    showChecked () {
      // this.$refs.tree.setCheckedKeys([])
      this.systemNodeFlag = true
      if (this.roleId !== '') {
        this.$axios.post(`/api/CommonMenu/showUserMenu/${this.roleId}`).then(({data}) => {
          let arr = []
          data.forEach((e, i) => {
            arr[i] = e.menuId
          })
          this.$refs.tree.setCheckedKeys(arr)
        })
      }
    },
    // 点击复选框时
    clickTreeCheckbox () {
      this.systemNodeFlag = false
    },
    // 提交的方法
    submitTree () {
      let checkedData = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      let arr = checkedData.sort(function (a, b) { return a - b })
      if (this.roleId !== '') {
        this.$confirm('确认修改该角色的菜单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // console.log(arr)
          const loading = this.$loading({
            lock: true,
            text: '正在努力修改角色菜单中，请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$axios.put(`/api/DHRoleMenuController/up?menus=${arr}&roleId=${this.roleId}`).then(result => {
            loading.close()
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            window.location.reload()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          })
        })
      } else {
        this.$message.error('请先选择角色后再提交！')
      }
    },
    // 禁用的方法
    delMenu1 (menuId) {
      this.$confirm('确定要禁用该菜单吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(`/api/DHMenuController/delMenu?menuId=${menuId}&menuState=1`).then(result => {
          this.$message({
            type: 'success',
            message: '禁用成功!'
          })
          this.initMenu()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        })
      })
    },
    // 恢复使用的方法
    delMenu2 (menuId) {
      this.$confirm('确定要重新启用该菜单吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(`/api/DHMenuController/delMenu?menuId=${menuId}&menuState=0`).then(result => {
          this.$message({
            type: 'success',
            message: '重新启用成功!'
          })
          this.initMenu()
        })
      }).catch(() => {

      })
    }
  },
  created () {
    this.showMenu()
  }
}
</script>
<style>
</style>
